#include "LayoutInterpolation.h"
#include "xVMRelationStruct.h"
#include "DIVA_VM.h"
#include "LayoutLibrary.h"
#include "DIVA_Application.h"
#include "CommandServer.h"

LayoutInterpolation*  LayoutInterpolation::_LayoutInterpolation = NULL;

LayoutInterpolation* LayoutInterpolation::getInstance(){
	if (_LayoutInterpolation == NULL) 
		_LayoutInterpolation = new LayoutInterpolation();
	return _LayoutInterpolation;
}

LayoutInterpolation::LayoutInterpolation(){
	_enable = true;
	_posttaked = false;
	_speed = 0;
	_time = 0;
	_frame = 100;
	_useVP = false;
}

void LayoutInterpolation::takePastSnapshot(){
	vector<DIVA_VM*> vms = xVMRelationStruct::getInstance()->VMRS_getAllVM();
	_evList.clear();
	for(int i=0; i<vms.size();i++){
		VMChangeEvent* tmp = new VMChangeEvent(vms.at(i) , _frame);
		_evList.push_back(tmp);
	}
	_posttaked = false;
	_cframe = 0;
}

void LayoutInterpolation::takePostSnapshot(){
	for (int i=0; i<_evList.size();i++){
		_evList.at(i)->setPostpos();
		_evList.at(i)->recover();
	}
	_posttaked = true;
}

void LayoutInterpolation::doInterpolation(float frame){
	if (_enable && _posttaked){
		for (int i=0; i<_evList.size();i++){
			_evList.at(i)->render(frame);
		}
	}
	else if(_enable){
		//takePastSnapshot();
		LayoutLibrary::getInstance()->doLayout();
		takePostSnapshot();
	}
	else{
		LayoutLibrary::getInstance()->doLayout();
	}
}

void LayoutInterpolation::setUseVP(bool b){
	_useVP = b;
}

void LayoutInterpolation::setTimer(float t){
	_time = t;
	const Ogre::RenderTarget::FrameStats& stats = DIVA_Application::getInstance()->getMwindow()->getStatistics();
	_frame = stats.avgFPS*t*0.8;
}